using System.Text.Json;
using System.Text.Json.Serialization;

namespace Digitalmes.Common.Extensions;

/// <summary>
/// JSON 扩展。
/// </summary>
public static class JsonExtensions
{
    private static readonly JsonSerializerOptions s_jsonOptions = new()
    {
        AllowTrailingCommas = true,
        PropertyNameCaseInsensitive = true,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        ReadCommentHandling = JsonCommentHandling.Skip,
    };

    /// <summary>
    /// JSON 反序列化。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="json"></param>
    /// <returns></returns>
    public static T? FromJson<T>(this string json) where T : class =>
        JsonSerializer.Deserialize<T>(json, s_jsonOptions);

    /// <summary>
    /// JSON 序列化。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <returns></returns>
    [return: NotNullIfNotNull(nameof(obj))]
    public static string? ToJson<T>(this T? obj) where T : class
    {
        if (obj == null)
        {
            return default;
        }

        return JsonSerializer.Serialize(obj, s_jsonOptions);
    }
}
